//
//  HttpRequest.m
//  HaoDeCaiFu
//
//  Created by 郑开宏 on 2017/10/31.
//  Copyright © 2017年 郑开宏. All rights reserved.
//

#import "HttpRequest.h"
#import "AFNetworking.h"
@implementation HttpRequest

+(void)sendPostRequestWithURL:(NSString *)url WithParamets:(NSDictionary *)dict WithJsonString:(NSString *)jsonString  success:(void(^)(id result))success failure:(void(^)(NSError *errer))failure {
    HttpRequest *h = [[HttpRequest alloc] init];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *newUrl;
    if (dict) {
        NSArray *keys = dict.allKeys;
        NSString *str;
        for (int i = 0; i < keys.count; i++) {
            NSString *key = keys[i];
            if (i == 0) {
                str = [NSString stringWithFormat:@"%@=%@&", key, dict[key]];
            }else{
                str = [NSString stringWithFormat:@"%@%@=%@&",str, key, dict[key]];
            }
        }
        NSString *allUrl = [NSString stringWithFormat:@"%@%@", KURLPost, str];
        //    NSString *newUrl = [allUrl stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        //    NSString *newUrl = [h URLEncodedString:allUrl];
        newUrl = [allUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    }else{
        newUrl = KURL;
    }
    
    NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:newUrl parameters:nil error:nil];
    manager.requestSerializer.timeoutInterval = 15.0;
    [req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    
    
    if (jsonString) {
        [req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
    }
    if (kToken) {
        [req setValue:[NSString stringWithFormat:@"Bearer %@", kToken] forHTTPHeaderField:@"Authorization"];
    }
    [[manager dataTaskWithRequest:req uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (!error) {
            success(responseObject);
        } else {
            failure(error);
        }
    }] resume];
}

- (NSString *)URLEncodedString:(NSString*)resource {
    CFStringRef url = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)resource, NULL, CFSTR("`#%^{}\"[]|\\<>+:"), kCFStringEncodingUTF8); // for some reason, releasing this is disasterous
    NSString *result = (__bridge NSString *)url;
    //    [result autorelease];
    return result;
}

+(void)sendGetRequestWithURL:(NSString *)url WithParamets:(NSDictionary *)param success:(void(^)(id result))success failure:(void(^)(NSError *errer))failure {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 15.0;
    NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"GET" URLString:[NSString stringWithFormat:@"%@", KURL] parameters:param error:nil];
    manager.requestSerializer.timeoutInterval = 15.0;
    [req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    if (kToken) {
        [req setValue:[NSString stringWithFormat:@"Bearer %@", kToken] forHTTPHeaderField:@"Authorization"];
    }
    [[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (!error) {
            success(responseObject);
        } else {
            failure(error);
        }
        
    }] resume];
//    [manager GET:KURL parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        success(responseObject);
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        failure(error);
//    }];
}


+(void)sendSelfPostRequestWithURL:(NSString *)url WithParamets:(NSString *)jsonString WithParamet:(NSDictionary *)dict success:(void(^)(id result))success failure:(void(^)(NSError *errer))failure {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"%@%@", KSelfUrl, url] parameters:dict error:nil];
    manager.requestSerializer.timeoutInterval = 15.0;
    [req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    if (kToken) {
        [req setValue:[NSString stringWithFormat:@"Bearer %@", kToken] forHTTPHeaderField:@"Authorization"];
    }
    [req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
//    if (kToken) {
//        [manager.requestSerializer setValue: forHTTPHeaderField:];
//    }
//    [[manager dataTaskWithRequest:req uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
//        
//    }] resume];
    
    [[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (!error) {
            success(responseObject);
        } else {
            failure(error);
        }
        
    }] resume];
}

+(void)sendSelfGetRequestWithURL:(NSString *)url WithParamets:(NSDictionary *)param success:(void(^)(id result))success failure:(void(^)(NSError *errer))failure {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 15.0;
    if (kToken) {
//        [manager setValue:[NSString stringWithFormat:@"Bearer %@", kToken] forHTTPHeaderField:@"Authorization"];
        [manager.requestSerializer setValue:[NSString stringWithFormat:@"Bearer %@", kToken]  forHTTPHeaderField:@"Authorization"];
    }
    [manager GET:[NSString stringWithFormat:@"%@%@", KSelfUrl, url] parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    }];
}

+(void)sendTwoSelfGetRequestWithURL:(NSString *)url WithParamets:(NSDictionary *)param success:(void(^)(id result))success failure:(void(^)(NSError *errer))failure {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 15.0;
    NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"GET" URLString:[NSString stringWithFormat:@"%@%@", KSelfUrl, url] parameters:param error:nil];
    manager.requestSerializer.timeoutInterval = 15.0;
    [req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    if (kToken) {
        [req setValue:[NSString stringWithFormat:@"Bearer %@", kToken] forHTTPHeaderField:@"Authorization"];
    }
    [[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (!error) {
            success(responseObject);
        } else {
            failure(error);
        }
     }] resume];
}

+(void)sendSelfPostTwoRequestWithURL:(NSString *)url WithParamets:(NSString *)jsonString WithParamet:(NSDictionary *)dict success:(void(^)(id result))success failure:(void(^)(NSError *errer))failure {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 15.0;
    NSString *u = [NSString stringWithFormat:@"%@%@?", KSelfUrl, url];
    NSArray *keys = dict.allKeys;
    NSString *str;
    for (int i = 0; i < keys.count; i++) {
        NSString *key = keys[i];
        if (i == 0) {
            str = [NSString stringWithFormat:@"%@=%@&", key, dict[key]];
        }else{
            str = [NSString stringWithFormat:@"%@%@=%@&",str, key, dict[key]];
        }
    }
    NSString *urlt = [NSString stringWithFormat:@"%@%@", u, [str substringToIndex:str.length - 1]];
    NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:urlt parameters:nil error:nil];
    [req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    if (kToken) {
        [req setValue:[NSString stringWithFormat:@"Bearer %@", kToken] forHTTPHeaderField:@"Authorization"];
    }
    [[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (!error) {
            success(responseObject);
        } else {
            failure(error);
        }
        
    }] resume];
}

@end
